package com.demons.demonsojcodesandbox.controller;

import com.demons.demonsojcodesandbox.JavaNativeCodeSandBox;
import com.demons.demonsojcodesandbox.model.ExecuteCodeResponse;
import com.demons.demonsojcodesandbox.model.ExecuteCondeRequest;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController("/")
public class MainController {

    //定义鉴权请求头和密钥
    public static final String AUTH_REQUEST_HEADER = "auth";
    public static final String AUTH_REQUEST_SECRET = "secretKey";
    @Resource
    private JavaNativeCodeSandBox javaNativeCodeSandBox;

    @GetMapping("/health")
    public String healthCheck() {
        return "ok";
    }

    /**
     * 执行代码
     *
     * @param executeCondeRequest
     * @return
     */
    @PostMapping("/executeCode")
    ExecuteCodeResponse executeCode(@RequestBody ExecuteCondeRequest executeCondeRequest,
                                    HttpServletRequest httpServletRequest,
                                    HttpServletResponse response){
        String authHeader = httpServletRequest.getHeader(AUTH_REQUEST_HEADER);
        if (!AUTH_REQUEST_SECRET.equals(authHeader)){
            response.setStatus(403);
            return null;
        }
        if (executeCondeRequest ==null){
            throw new RuntimeException("请求参数为空");
        }

        return javaNativeCodeSandBox.executeCode(executeCondeRequest);
    }
}
